import sys

import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText  # 往邮件中写内容的对象

from email.utils import formataddr  # 发件人信息
import sqlite3
# 目标网址
import time
import random
import string
import sqlite3
from datetime import datetime

global rst
# 创建数据库连接
conn = sqlite3.connect('E:\sqlite\GooglePlayAppsLink.db')
cursor = conn.cursor()
# 创建一个Cursor对象，并使用它执行SQL语句
# cursor = conn.cursor()
# # 关闭Cursor对象
# cursor.close()
# # 关闭数据库连接
# conn.close()

# msg_from = 'aleanchan@foxmail.com'
# password = 'ipanktlpktaeffie'
#
# msg_from = 'aleangmx@foxmail.com'
# password = 'hyfcoojcmkmndghh'
#
# msg_from = 'easyzaki@foxmail.com'
# password = 'ymkwowhoxevdbdbb'

accounts = [
    ['aleanp@foxmail.com','xdplfkagbasybdda'],
    ['aleangmx@foxmail.com','hyfcoojcmkmndghh'],
    ['aleanchan@foxmail.com','ipanktlpktaeffie'],
    ['easyzaki@foxmail.com','ymkwowhoxevdbdbb'],
]

def getMail(url,account1):

    # 发送HTTP请求
    response = requests.get(url)
    # 确保网页请求成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析网页内容
        try:
            soup = BeautifulSoup(response.text, 'html.parser')
            emaili = soup.find('i', string='email')
            details = emaili.parent.find_all('div', class_='pSEeg')
            detail = details[len(details) - 1]
            updatetime = soup.find('div', class_='xg1aie').text

            emaili = soup.find('div', string='Downloads')
            downloads = emaili.parent.find('div', class_='ClM7O').text
        except:
            return

        target_mail = detail.text
        print(url, target_mail, downloads, updatetime,account1[0])
        packagename = url[url.index("=") + 1:]
        try:
            now = datetime.now()
            formatted_now = now.strftime('%Y-%m-%d %H:%M:%S')
            cursor.execute(
                'INSERT INTO links (package_name, link,downloads,app_update_time,target_mail,insert_time) VALUES (?,?,?,?,?,?)',
                (packagename, url, downloads, updatetime, target_mail, formatted_now))
            conn.commit()
        except:
            pass

        cursor.execute('SELECT count(*) FROM links where is_sent = 1 and target_mail=?', (target_mail,))
        results = cursor.fetchall()

        if not target_mail.endswith('google.com') and not downloads.__contains__('M') and not downloads.__contains__(
                '00K') and not updatetime.__contains__('2024') and int(results[0][0]) == 0:
            if send(target_mail, url,account1):
                try:
                    now = datetime.now()
                    formatted_now = now.strftime('%Y-%m-%d %H:%M:%S')
                    cursor.execute(
                        'UPDATE links SET is_sent = 1, send_mail = ?, update_time=? WHERE package_name =  ?', (account1[0], formatted_now,packagename))
                    conn.commit()
                except:
                    pass

            time.sleep(30)
    else:
        print(f"Error: {response.status_code}")


# 注意：爬取过程可能受到robots.txt的限制，以及需要处理网页内容的加载和Ajax动态内容的抓取等复杂情况
def getLinks(keywords, account1):

    # 发送HTTP请求
    q_keywords = 'https://play.google.com/store/search?c=apps&q=' + keywords
    response = requests.get(q_keywords)
    print(q_keywords)
    # 确保网页请求成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析网页内容
        soup = BeautifulSoup(response.text, 'html.parser')
        details = soup.find_all('a', class_='Si6A0c')
        for detail in details:
            global rst
            if rst:
                link = 'https://play.google.com' + detail['href']
                getMail(link, account1)
    else:
        print(f"Error: {response.status_code}")


def send(mail, url,account1):
    # 2 发送方和接收方配置
    # 发件方邮箱：谁发送的
    # msg_from = 'alean@wwstudio.site'
    # # 生成的授权码：不能泄露
    # password = 'e25ed6c8bfae07dd548d7c8359c5a866'

    # # 发送给谁，可以写多个人，以列表形式存储
    msg_to = [mail]
    # 邮件主题
    subject = "Buying idle Google Play Console accounts at high prices!"  # 主题
    content = "Hello Developer,\nWe see that your Google Play Console account has been idle for a long time. If you no longer use it, you can sell it to us. We have estimated the price. This will be a very considerable income.\n\nLooking forward to your reply\nThank you!\n\nYours,\nAlean\n\n" + url  # 邮件内容
    # 生成一个MIMEText对象（还有一些其它参数）
    msg = MIMEText(content)
    # 放入邮件主题
    msg['Subject'] = subject
    # 放入发件人,元祖中内容第一个是发件人名称，第二个是发件地址
    msg['From'] = formataddr(('Google Play', account1[0]))
    # 放入收件人,将收件人转化为以逗号分隔的字符串
    msg['to'] = ','.join(msg_to)
    # s = smtplib.SMTP_SSL("smtp.sendcloud.net", 587)
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    result = False
    ee =''

    try:
        # 通过ssl方式发送，服务器地址，端口
        # 登录到邮箱
        s.login(account1[0], account1[1])
        # 发送邮件：发送方，收件方，要发送的消息
        s.sendmail(account1[0], msg_to, msg.as_string())  # 第二个参数可以以列表的方式写多个
        print('成功')
        result = True
    except BaseException as e:
        print(e)
        ee = e

    finally:
        # 不管是否发送成功，都退出服务
        try:
            s.quit()
        except:
            pass
        global rst
        if ee.__str__().__contains__('550'):
            rst = False
        return result


for account1 in accounts:
    global rst
    rst = True
    while rst:
        # 这里是死循环的内容
        letters = string.ascii_letters
        # 随机生成四位字母
        four_letter_code = ''.join(random.choices(letters, k=5))
        getLinks(four_letter_code,account1)
